﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SCG.General
{
    public class ByteMatrix : BaseMatrix
    {
        //constructor
        public ByteMatrix(int width, int height)
        {
            _matrix = new byte[width, height];
            _width = width;
            _height = height;
        }
        public ByteMatrix(string s)
        {
            string[] contents = s.Split('\r', '\n');
            List<string> lines = new List<string>();
            foreach (string line in contents)
                if (line.Trim() != "")
                    lines.Add(line);
            _width = lines[0].Length;
            _height = lines.Count;
            _matrix = new byte[_width, _height];
            for (int y = 0; y < lines.Count; y++)
            {
                string line = lines[y];
                for (int x = 0; x < _width; x++)
                {
                    byte value = Byte.Parse(line[x] + "");
                    _matrix[x, y] = value;
                }
            }
        }

        //fill with a value
        public void Fill(byte value)
        {
            for (int y = 0; y < _height; y++)
                for (int x = 0; x < _width; x++)
                    _matrix[x, y] = value;
        }

        //get/set values
        public byte Get(int x, int y)
        {
            return _matrix[x, y];
        }
        public byte GetSafely(int x, int y)
        {
            if (InBounds(x, y))
                return _matrix[x, y];
            else
                return 0;
        }
        public void Set(int x, int y, byte value)
        {
            _matrix[x, y] = value;
        }
        public void SetSafely(int x, int y, byte value)
        {
            if (InBounds(x, y))
                _matrix[x, y] = value;
        }

        //add one byte matrix to another, with a maximum value
        public void Add(ByteMatrix matrix, int x, int y, byte maxValue)
        {
            for(int my = 0; my < matrix.Height; my++)
                for (int mx = 0; mx < matrix.Width; mx++)
                {
                    int i = matrix.Get(mx, my);
                    int n = GetSafely(mx + x, my + y);
                    int v = i + n;
                    if (v > maxValue)
                        v = maxValue;
                    SetSafely(mx + x, my + y, (byte)v);
                }
        }

        //private members
        private byte[,] _matrix;
    }
}
